package dataStructure.tree;

//二叉排序树
public class BinarySortTreeDemo {
    public static void main(String[] args) {
        int[] data = {7,3,10,12,5,1,9};
        BinarySortTree binarySortTree = new BinarySortTree();
        for (int i = 0; i < data.length; i++) {
            binarySortTree.add(new Node(data[i]));
        }
        binarySortTree.infixOrder();
    }

}
class BinarySortTree {
    private Node root;
    BinarySortTree(){

    }

    public Node getRoot() {
        return root;
    }

    public void setRoot(Node root) {
        this.root = root;
    }
    public void add(Node node){
        if (root==null){
            root = node;
        }else {
            root.add(node);
        }
    }

    public void infixOrder(){
        if (root!=null){
            root.infixOrder();
        }else {
            System.out.println("二叉排序树为空");
        }
    }
}

//创建结点
class Node {
    public int value;
    public Node left;
    public Node right;

    Node(int value) {
        this.value = value;
    }


    public void add(Node node) {
        if (node.value < this.value) {
            if (this.left == null) {
                this.left = node;
            } else {
                this.left.add(node);
            }
        } else {
            if (this.right == null) {
                this.right = node;
            } else {
                this.right.add(node);
            }
        }
    }


    public void infixOrder() {
        if (this.left != null) {
            this.left.infixOrder();
        }
        System.out.println(this);
        if (this.right != null) {
            this.right.infixOrder();
        }

    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }
}